package com.atguigu.tingshu.live.service.impl;
import java.math.BigDecimal;

import com.atguigu.tingshu.live.util.LiveAutoAddressUtil;
import com.atguigu.tingshu.vo.live.TencentLiveAddressVo;
import com.google.common.collect.Maps;

import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.live.mapper.LiveRoomMapper;
import com.atguigu.tingshu.live.service.LiveRoomService;
import com.atguigu.tingshu.model.live.LiveRoom;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class LiveRoomServiceImpl extends ServiceImpl<LiveRoomMapper, LiveRoom> implements LiveRoomService {

	@Autowired
	private LiveRoomMapper liveRoomMapper;

	@Override
	public LiveRoom getCurrentLive() {

		// 获取当前登录用户的id
		Long userId = AuthContextHolder.getUserId();
		LambdaQueryWrapper<LiveRoom> lambdaQueryWrapper = new LambdaQueryWrapper<>() ;
		lambdaQueryWrapper.eq(LiveRoom::getUserId , userId) ;
		lambdaQueryWrapper.gt(LiveRoom::getExpireTime , new Date()) ;
		LiveRoom liveRoom = liveRoomMapper.selectOne(lambdaQueryWrapper);

		// 返回
		return liveRoom ;
	}

	@Override
	public LiveRoom saveLiveRoom(LiveRoom liveRoom) {

		// 根据当前登录的用户id和直播间的过期时间进行数据查询
		LiveRoom dbLiveRoom = getCurrentLive();
		if(dbLiveRoom != null) {
			return dbLiveRoom ;
		}

		// 新增直播间数据
		Long userId = AuthContextHolder.getUserId();
		liveRoom.setUserId(userId);
		liveRoom.setStatus("1");
		liveRoom.setAppName("live");
		String streamName = "atguigu_" + userId ;
		liveRoom.setStreamName(streamName);
		long txTime = liveRoom.getExpireTime().getTime() / 1000 ;
		TencentLiveAddressVo tencentLiveAddressVo = LiveAutoAddressUtil.getAddressUrl(streamName, txTime);
		String pushWebRtcUrl = tencentLiveAddressVo.getPushWebRtcUrl();
		String pullWebRtcUrl = tencentLiveAddressVo.getPullWebRtcUrl();
		liveRoom.setPushUrl(pushWebRtcUrl);
		liveRoom.setPlayUrl(pullWebRtcUrl);
		liveRoomMapper.insert(liveRoom) ;


		return liveRoom;
	}

	@Override
	public List<LiveRoom> findLiveList() {
//		Long userId = AuthContextHolder.getUserId();
		LambdaQueryWrapper<LiveRoom> lambdaQueryWrapper = new LambdaQueryWrapper<>() ;
		lambdaQueryWrapper.gt(LiveRoom::getExpireTime , new Date());
//		lambdaQueryWrapper.notIn(LiveRoom::getUserId , userId) ;
		List<LiveRoom> liveRoomList = liveRoomMapper.selectList(lambdaQueryWrapper);
		return liveRoomList;
	}

}
